/**
 * Created with JetBrains WebStorm.
 * User: Endre Balogh
 * Date: 6/11/13
 * Time: 1:04 PM
 * To change this template use File | Settings | File Templates.
 */

'use strict';

angular.module('module.ender.game.character.feats', [])
    .value('featTypeNames', {
        "combat": "Combat",
        "saves": "Saves",
        "general": "General",
        "skills": "Skills"
    })
    .value('featTypeOrders', {
        "combat": 1,
        "saves": 3,
        "general": 2,
        "skills": 4
    })
    .factory('featHelper', function (featTypeNames, featTypeOrders) {
        return {
            /**
             * Groups the feats into categories based on type, and returns an array of the categories.
             * @param {Array} featList
             * @returns {Array}
             */
            buildFeatCategoryArray: function (featList) {
                var featCategoryHash = {};

                for (var i = 0, length = featList.length; i < length; i++) {
                    var feat = featList[i];
                    if (!featCategoryHash[feat.type]) {
                        featCategoryHash[feat.type] = [];
                    }
                    featCategoryHash[feat.type].push(feat);
                }

                var array = [];
                for (var featType in featCategoryHash) {
                    array.push({
                        name: featTypeNames[featType],
                        order: featTypeOrders[featType],
                        feats: featCategoryHash[featType]
                    });
                }
                return array;
            }
        }
    })
    .factory('featRepository', function factoryFunction($resource, $q) {
        var resource = $resource('data/feats.json');
        var deferred = $q.defer();
        var featsResource = resource.get(function () {
            for (var featId in featsResource) {
                if (featsResource.hasOwnProperty(featId)) {
                    var feat = featsResource[featId];
                    feat.id = featId;
                }
            }

            deferred.resolve();
        });

        return {
            /**
             * Returns the feats with the given ids. The result is an empty array, which will be filled when the data will be available.
             * @param {Array} featIdList
             * @returns {Array}
             */
            getFeatsByIds: function (featIdList) {
                var feats = [];

                deferred.promise.then(function () {
                    for (var i = 0; i < featIdList.length; i++) {
                        var featId = featIdList[i];
                        feats.push(featsResource[featId]);
                    }
                });

                return feats;
            }
        }
    });